
import { MarkersAction, MarkersActionTypes } from '../actions';

import { Marker } from '../../models';

export interface MarkersState {
    entities: { [id: number]: Marker },
    lastId: number,
    lastRemove: Marker,
    lastAdd: Marker,
    clear: boolean
}

export const initialMarkersState: MarkersState = {
    entities: {},
    lastId: 0,
    lastAdd: null,
    lastRemove: null,
    clear: false
};

export function markersReducer(state: MarkersState = initialMarkersState, action: MarkersAction): MarkersState {
    switch(action.type) {
        case MarkersActionTypes.ADD_MARKER: {
            const lastId: number = state.lastId + 1;
            const payload: Marker = {...action.payload, id: lastId };
            const entities: { [id: number]: Marker } = {...state.entities, [lastId]: payload };
            return {
                ...state,
                entities,
                lastId,
                lastAdd: payload,
                lastRemove: null,
                clear: false
            }
        }
        case MarkersActionTypes.REMOVE_MARKER: {
            const payload: Marker = action.payload;
            const { [payload.id]: removed, ...entities } = state.entities;
            return {
                ...state,
                entities,
                lastAdd: null,
                lastRemove: removed,
                clear: false
            }
        }
        case MarkersActionTypes.CLEAR_MARKER: {
            return {
                ...state,
                entities: {},
                lastAdd: null,
                lastRemove: null,
                clear: true
            };
        }
        default: {
            return state;
        }
    }
}